package com.gcu.drivingschool.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gcu.drivingschool.domain.dto.PageBean;
import com.gcu.drivingschool.domain.dto.UpdateScoreDto;
import com.gcu.drivingschool.domain.po.Score;
import com.gcu.drivingschool.domain.po.Student;
import com.gcu.drivingschool.domain.vo.Result;
import com.gcu.drivingschool.service.ScoreService;
import com.gcu.drivingschool.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author zzr
 * @since 2024-06-24
 */
@RestController
@RequestMapping("/scores")
@RequiredArgsConstructor
@Tag(name = "模拟考试分数控制器",description = "模拟考试分数控制器")
public class ScoreController {
    private final ScoreService scoreService;
    private final StudentService studentService;

    /**
     * 记录分数
     *
     * @param score
     * @return
     */
    @Operation(summary = "记录分数", description = "记录分数")
    @PostMapping
    public Result addScore(@RequestBody @Validated Score score) {
        String subject = score.getSubject();
        BigDecimal passScore = "科目二".equals(subject) ? BigDecimal.valueOf(80) : BigDecimal.valueOf(90);
        score.setStatus(score.getScore().compareTo(passScore) >= 0 ? "合格" : "不合格");
        if (score.getSubject().equals("科目一")||score.getSubject().equals("科目四")) {
            score.setExamTime(LocalDate.now());
        }
        if (scoreService.save(score)) {
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 查询考试成绩记录列表
     *
     * @param pageNum
     * @param pageSize
     * @param studentId
     * @param coachId
     * @return
     */
    @Parameters({
            @Parameter(name = "pageNum", description = "第几页", in = ParameterIn.QUERY),
            @Parameter(name = "pageSize", description = "每页条数", in = ParameterIn.QUERY),
            @Parameter(name = "studentId", description = "学员id", in = ParameterIn.QUERY),
            @Parameter(name = "coachId", description = "教练id", in = ParameterIn.QUERY),
            @Parameter(name = "subject", description = "科目（科目一，科目二，科目三，科目四）", in = ParameterIn.QUERY),
    })
    @Operation(summary = "查询考试成绩记录列表", description = "查询考试成绩记录列表")
    @GetMapping
    public Result getBookDrivingList(@RequestParam(required = false) Integer pageNum,
                                     @RequestParam(required = false) Integer pageSize,
                                     @RequestParam(required = false) Integer studentId,
                                     @RequestParam(required = false) Integer coachId,
                                     @RequestParam(required = false) String subject) {
        //如果不传pageNum和pageSize,不分页
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = Integer.MAX_VALUE;
        }
        PageBean pb = new PageBean(0L, new ArrayList());
        LambdaQueryWrapper<Score> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(studentId != null, Score::getStudentId, studentId)
                .eq(StringUtils.isNotBlank(subject), Score::getSubject, subject);
        if (coachId != null) {
            //查询教练所有学员id
            List<Integer> sIds = studentService.lambdaQuery().eq(Student::getCoachId, coachId).list()
                    .stream().mapToInt(Student::getId).boxed().collect(Collectors.toList());
            if (sIds.size() > 0) {
                wrapper.in(Score::getStudentId, sIds);
            } else {
                return Result.success(pb);
            }
        }
        PageHelper.startPage(pageNum, pageSize);//分页
        //查询数据
        List<Score> list = scoreService.list(wrapper);
        Page p = (Page) list;
        List<Score> r = p.getResult();
        //查询该记录学员详细信息（也可用联表查询）
        for (Score b : r) {
            Student student = studentService.getById(b.getStudentId());
            b.setStudentName(student.getName());
        }
        pb = new PageBean(p.getTotal(), r);
        return Result.success(pb);
    }


    /**
     * 删除记录
     *
     * @param id
     * @return
     */
    @Parameter(name = "id", description = "预约记录id", in = ParameterIn.PATH, required = true)
    @Operation(summary = "删除记录", description = "删除记录")
    @DeleteMapping("/{id}")
    public Result delRecord(@PathVariable("id") Integer id) {
        boolean remove = scoreService.removeById(id);
        if (!remove) {
            return Result.fail();
        }
        return Result.success();
    }

    @Operation(summary = "修改记录", description = "修改记录")
    @PutMapping
    public Result updateScore(@Validated @RequestBody UpdateScoreDto updateScoreDto){
        LambdaUpdateWrapper<Score> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(updateScoreDto.getScore()!=null,Score::getScore,updateScoreDto.getScore())
                        .set(StringUtils.isNotBlank(updateScoreDto.getSubject()),Score::getSubject,updateScoreDto.getSubject())
                .eq(Score::getId,updateScoreDto.getId());
        if (scoreService.update(wrapper)) {
            return Result.success();
        }
        return Result.fail();
    }
}
